﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AurelienRibon.Core.Options;
using System.IO;
using System.Xml.Linq;
using System.Diagnostics;

namespace CodeIn.Core {
	public class OptionManager : OptionRepository {
		private static OptionManager instance = new OptionManager();
		public static OptionManager Instance { get { return instance; } }

		private OptionManager() {
		}

		/// <summary>
		/// Saves every option value in a .xml file.
		/// </summary>
		public void Save() {
			string path = ResourceManager.Instance.Paths["OptionFilePath"].Path;

			FileInfo fileInfo = new FileInfo(path);
			if (!fileInfo.Exists)
				Directory.CreateDirectory(Path.GetDirectoryName(fileInfo.FullName));

			XDocument doc = new XDocument(
				new XElement("Options",
					from opt in RegisteredOptions.Values
					select new XElement("Option",
						new XAttribute("Name", opt.Name),
						opt.Value)
				)
			);

			doc.Save(path);
		}

		/// <summary>
		/// Loads the options from a .xml file. Options must have been created
		/// before calling this method (and that's easily explained).
		/// </summary>
		public void Load() {
			string path = ResourceManager.Instance.Paths["OptionFilePath"].Path;

			if (File.Exists(path)) {
				XDocument doc = XDocument.Load(path);
				var tuples = from opt in doc.Root.Elements("Option")
							 select new Tuple<string, string>(opt.Attribute("Name").Value, opt.Value);

				foreach (var tuple in tuples) {
					try {
						var opt = GetOptionFromName(tuple.Item1);
						opt.Value = tuple.Item2;
					} catch (OptionNotRegisteredException ex) {
						Debug.WriteLine("Option not found while loading: " + tuple.Item1);
					}
				}
			} else {
				Debug.WriteLine("Could not find the option file");
			}
		}
	}
}
